<?php
/**
 * 设备指令下发API - PHP测试脚本
 * 使用方法: php docs/test_device_api.php
 */

class DeviceApiTester
{
    private $apiKey = 'ak_3d97ebf664db97f3023b336f5fc0ad23';
    private $secretKey = 'e61b4d35cf2a29e46e08e36dd075ea585614cd91470719c4411d2b946f677e12';
    private $baseUrl = 'http://localhost:8000';
    
    /**
     * 生成API签名
     */
    private function generateSignature($method, $path, $timestamp, $body)
    {
        $stringToSign = strtoupper($method) . "\n" . $path . "\n" . $timestamp . "\n" . $body;
        return hash_hmac('sha256', $stringToSign, $this->secretKey);
    }
    
    /**
     * 发送API请求
     */
    private function sendRequest($method, $path, $data = [])
    {
        $url = $this->baseUrl . '/' . $path;
        $timestamp = time();
        $body = empty($data) ? '' : json_encode($data, JSON_UNESCAPED_UNICODE);
        $signature = $this->generateSignature($method, $path, $timestamp, $body);
        
        // 构建请求头
        $headers = [
            'Authorization: ApiKey ' . $this->apiKey,
            'Timestamp: ' . $timestamp,
            'Signature: ' . $signature,
            'Content-Type: application/json',
            'X-Request-ID: req_' . uniqid()
        ];
        
        echo "=== 发送请求 ===\n";
        echo "URL: {$url}\n";
        echo "方法: {$method}\n";
        echo "请求体: {$body}\n";
        echo "时间戳: {$timestamp}\n";
        echo "签名: {$signature}\n";
        echo "请求头:\n";
        foreach ($headers as $header) {
            echo "  {$header}\n";
        }
        echo "\n";
        
        // 初始化cURL
        $ch = curl_init();
        
        // 设置基本选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        // 设置HTTP方法
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        } elseif ($method === 'GET') {
            curl_setopt($ch, CURLOPT_HTTPGET, true);
        } else {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            if (!empty($body)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
            }
        }
        
        // 执行请求
        $startTime = microtime(true);
        $response = curl_exec($ch);
        $endTime = microtime(true);
        
        // 获取响应信息
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        // 输出响应信息
        echo "=== 响应结果 ===\n";
        echo "HTTP状态码: {$httpCode}\n";
        echo "Content-Type: {$contentType}\n";
        echo "响应时间: " . round(($endTime - $startTime) * 1000, 2) . "ms\n";
        echo "cURL总时间: " . round($totalTime * 1000, 2) . "ms\n";
        
        if ($error) {
            echo "cURL错误: {$error}\n";
        }
        
        echo "响应内容:\n";
        if ($response) {
            // 尝试格式化JSON响应
            $jsonData = json_decode($response, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                echo json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
            } else {
                echo $response . "\n";
            }
        } else {
            echo "无响应内容\n";
        }
        
        echo "\n" . str_repeat("-", 60) . "\n\n";
        
        return [
            'success' => $httpCode >= 200 && $httpCode < 300,
            'http_code' => $httpCode,
            'response' => $response,
            'data' => $jsonData ?? null,
            'error' => $error
        ];
    }
    
    /**
     * 测试设备重启
     */
    public function testReboot()
    {
        echo "### 测试1: 设备重启 ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'mac' => '1C3426522542',
            'type' => 'reboot'
        ]);
    }
    
    /**
     * 测试热点配置
     */
    public function testHotspotConfig()
    {
        echo "### 测试2: 热点配置 ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '863780074784151',
            'type' => 'hotspot_config'
        ]);
    }
    
    /**
     * 测试SIM卡切换
     */
    public function testSimSwitch()
    {
        echo "### 测试3: SIM卡切换到槽1 ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '863780074784151',
            'type' => 'sim_switch_slot1'
        ]);
    }

    /**
     * 测试网络限速
     */
    public function testSpeedLimit()
    {
        echo "### 测试4: 网络限速10MB ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '863780074784151',
            'type' => 'speed_limit_10m'
        ]);
    }

    /**
     * 测试立即上报
     */
    public function testReportStatus()
    {
        echo "### 测试5: 立即上报状态 ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '863780074784151',
            'type' => 'report_status'
        ]);
    }
    
    /**
     * 测试获取支持的指令
     */
    public function testGetCommands()
    {
        echo "### 测试6: 获取支持的指令类型 ###\n";
        return $this->sendRequest('GET', 'api/device/commands');
    }

    /**
     * 测试获取API示例
     */
    public function testGetExamples()
    {
        echo "### 测试7: 获取API示例 ###\n";
        return $this->sendRequest('GET', 'api/device/command/examples');
    }
    
    /**
     * 测试错误情况 - 无效IMEI
     */
    public function testInvalidImei()
    {
        echo "### 测试8: 错误测试 - 无效IMEI ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '123456789',  // 无效的IMEI
            'type' => 'reboot'
        ]);
    }

    /**
     * 测试错误情况 - 无效指令类型
     */
    public function testInvalidType()
    {
        echo "### 测试9: 错误测试 - 无效指令类型 ###\n";
        return $this->sendRequest('POST', 'api/device/command', [
            'imei' => '863780074784151',
            'type' => 'invalid_command'  // 无效的指令类型
        ]);
    }
    
    /**
     * 运行所有测试
     */
    public function runAllTests()
    {
        echo "=== 设备指令下发API - PHP测试脚本 ===\n";
        echo "API Key: {$this->apiKey}\n";
        echo "Base URL: {$this->baseUrl}\n";
        echo "测试时间: " . date('Y-m-d H:i:s') . "\n\n";
        
        $tests = [
            'testReboot',
            // 'testHotspotConfig', 
            // 'testSimSwitch',
            // 'testSpeedLimit',
            // 'testReportStatus',
            // 'testGetCommands',
            // 'testGetExamples',
            // 'testInvalidImei',
            // 'testInvalidType'
        ];
        
        $results = [];
        $successCount = 0;
        $totalCount = count($tests);
        
        foreach ($tests as $test) {
            $result = $this->$test();
            $results[$test] = $result;
            
            if ($result['success']) {
                $successCount++;
            }
            
            // 每个测试之间暂停1秒
            sleep(1);
        }
        
        // 输出测试总结
        echo "=== 测试总结 ===\n";
        echo "总测试数: {$totalCount}\n";
        echo "成功数: {$successCount}\n";
        echo "失败数: " . ($totalCount - $successCount) . "\n";
        echo "成功率: " . round(($successCount / $totalCount) * 100, 2) . "%\n\n";
        
        echo "详细结果:\n";
        foreach ($results as $testName => $result) {
            $status = $result['success'] ? '✅ 成功' : '❌ 失败';
            echo "  {$testName}: {$status} (HTTP {$result['http_code']})\n";
        }
        
        return $results;
    }
}

// 运行测试
if (php_sapi_name() === 'cli') {
    $tester = new DeviceApiTester();
    $tester->runAllTests();
} else {
    echo "请在命令行中运行此脚本: php " . __FILE__;
}
